package com.ncu702.backend.controller;


import com.ncu702.backend.common.BaseResponse;
import com.ncu702.backend.common.ErrorCode;
import com.ncu702.backend.common.ResultUtils;
import com.ncu702.backend.model.entity.User;
import com.ncu702.backend.model.untils.TokeConfig;
import com.ncu702.backend.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.UrlResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/api/avatar")
@Slf4j
public class AvatarController {


    @Resource
    private UserService userService;
    @Resource
    private TokeConfig tokeConfig;


    //用户上传图片
    @PostMapping("/upload")
    public BaseResponse<Integer> handleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request)
            throws IOException {

        String jwt = request.getHeader("jwtToken");
        //鉴权
        boolean checkToke = tokeConfig.checkToke(jwt);
        if(!checkToke){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR,"token失效");
        }
        User jwtToken = tokeConfig.getTokeMessage(jwt);

        // 获取文件名
        String fileName = file.getOriginalFilename();
        //处理文件重名问题
        String hzName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + hzName;
        // 获取jar包所在目
        String jarPath = new File(AvatarController.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent();
        // 构建上传文件目标路径
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
        String dateStr = simpleDateFormat.format(new Date());
        String uploadPath = jarPath + File.separator + "upload" + File.separator + dateStr + fileName;
        String recordPath = File.separator +"upload" + File.separator + dateStr + fileName;
        // 创建上传文件目录
        File uploadDir = new File(jarPath + File.separator + "upload"+ File.separator + dateStr);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        // 保存上传文件
        File dest = new File(uploadPath);
        file.transferTo(dest);
        int i = userService.UploadPicture(jwtToken.getUid(), recordPath);
        return  ResultUtils.success(i);
    }


    @GetMapping("/download")
    public  BaseResponse<String> downloadFile(HttpServletRequest request) throws IOException {

        String jwtToken = request.getHeader("jwtToken");
        //鉴权
        boolean checkToke = tokeConfig.checkToke(jwtToken);

        if(!checkToke){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR,"token失效");
        }

        User tokeMessage = tokeConfig.getTokeMessage(jwtToken);
        Long uid = tokeMessage.getUid();
        //获取用户图片
        User user = userService.UserByUid(uid);
        String userAvatar = user.getUserAvatar();

        // 获取要下载的文件
        //jar包运行路径
        String jarPath = new File(AvatarController.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent();

        Path filePath = Paths.get(jarPath + userAvatar);

        // 检查文件是否存在
        if (!Files.exists(filePath)) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR);

        }

        UrlResource resource =new UrlResource(filePath.toUri());
        byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
        String base64String = "data:image/jpg;base64,"+ new String(Base64.getEncoder().encode(bytes));

        // 设置响应头

        // 返回文件的响应实体
        return ResultUtils.success(base64String);
    }


    @GetMapping("/downloadByUid")
    public  BaseResponse<String> downloadFileByUid(@RequestParam("uid")Long uid , HttpServletRequest request) throws IOException {

//        String jwtToken = request.getHeader("jwtToken");
//        //鉴权
//        boolean checkToke = tokeConfig.checkToke(jwtToken);
//
//        if(!checkToke){
//            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR,"token失效");
//        }

        //获取用户图片
        User user = userService.UserByUid(uid);
        String userAvatar = user.getUserAvatar();

        // 获取要下载的文件
        //jar包运行路径
        String jarPath = new File(AvatarController.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent();

        Path filePath = Paths.get(jarPath + userAvatar);

        // 检查文件是否存在
        if (!Files.exists(filePath)) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR);

        }

        UrlResource resource =new UrlResource(filePath.toUri());
        byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
        String base64String = "data:image/jpg;base64,"+ new String(Base64.getEncoder().encode(bytes));

        // 设置响应头

        // 返回文件的响应实体
        return ResultUtils.success(base64String);
    }

}
